import os
import json
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLineEdit, QLabel, QProgressBar, QHBoxLayout
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont, QPixmap
from qfluentwidgets import SmoothScrollArea, PrimaryPushButton, InfoBar, InfoBarPosition
from modules import MatrixModule, PointsModule, CombinerModule, QuadrantModule
from visualize import Animation3D
from run_experiments import run_path_planning


class BatchInterface(SmoothScrollArea):  # 修改为继承 SmoothScrollArea
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.view = QWidget(self)
        self.vBoxLayout = QVBoxLayout(self.view)
        self.setWidget(self.view)
        self.setWidgetResizable(True)

        # 将背景样式直接应用到主视图，修改图片路径指向pic文件夹中的背景图片
        self.view.setStyleSheet('''
            QWidget#mainView {
                border-image: url(pic/background2.png) 0 0 0 0 stretch stretch;
            }
        ''')
        self.view.setObjectName("mainView")

        # 添加中间层图片，修改图片路径指向pic文件夹
        self.bg_image = QLabel(self.view)
        self.bg_image.setPixmap(QPixmap("pic/yijianyunxing.png"))
        self.bg_image.setScaledContents(True)  # 允许图片缩放
        self.bg_image.setStyleSheet('background: transparent;')
        self.bg_image.lower()  # 将图片置于底层，但在背景之上

        # 确保滚动区域和其他组件保持透明
        self.setStyleSheet('''
            QScrollArea {
                border: none;
                background: transparent;
            }
            QLabel {
                background: transparent;
                color: white;
            }
            QLineEdit {
                background: transparent;
                border: 1px solid white;
                border-radius: 4px;
                padding: 4px;
                color: white;
            }
            QProgressBar {
                background: transparent;
                border: 1px solid white;
                color: white;
            }
        ''')

        self.animation_window = None
        self.initUI()

    def initUI(self):
        self.vBoxLayout.setAlignment(Qt.AlignCenter)
        self.vBoxLayout.setSpacing(60)  # 增大控件间距

        # 增加顶部空白，将整体内容向下移动
        self.vBoxLayout.addSpacing(200)  # 从100增加到200

        # 删除标题相关代码

        # 创建输入框
        self.inputs = {}
        input_configs = {
            'rows': ('', '10'),  # 删除标签文字
            'cols': ('', '10'),  # 删除标签文字
            'obstacles': ('', '20'),  # 删除标签文字
            'points': ('', '3')  # 删除标签文字
        }

        for key, (label_text, default) in input_configs.items():
            # 创建水平布局来放置标签和输入框
            input_layout = QHBoxLayout()
            input_layout.setAlignment(Qt.AlignCenter)

            # 修改标签的背景图片，指向pic文件夹中的对应图片
            if key == 'rows':
                # 矩阵行数标签使用 juxing2.png
                label = QLabel()
                pixmap = QPixmap("pic/juxing2.png")
                label.setFixedSize(200, 60)
                label.setStyleSheet('''
                    QLabel {
                        border-image: url(pic/juxing2.png);
                        background-position: center;
                        background-repeat: no-repeat;
                    }
                ''')
            elif key == 'cols':
                # 矩阵列数标签使用 juxing.png
                label = QLabel()
                pixmap = QPixmap("pic/juxing.png")
                label.setFixedSize(200, 60)
                label.setStyleSheet('''
                    QLabel {
                        border-image: url(pic/juxing.png);
                        background-position: center;
                        background-repeat: no-repeat;
                    }
                ''')
            elif key == 'obstacles':
                # 障碍物数量标签使用 zhangaiwushuliang.png
                label = QLabel()
                pixmap = QPixmap("pic/zhangaiwushuliang.png")
                label.setFixedSize(200, 60)
                label.setStyleSheet('''
                    QLabel {
                        border-image: url(pic/zhangaiwushuliang.png);
                        background-position: center;
                        background-repeat: no-repeat;
                    }
                ''')
            elif key == 'points':
                # 点对数量标签使用 dianduishuliang.png
                label = QLabel()
                pixmap = QPixmap("pic/dianduishuliang.png")
                label.setFixedSize(200, 60)
                label.setStyleSheet('''
                    QLabel {
                        border-image: url(pic/dianduishuliang.png);
                        background-position: center;
                        background-repeat: no-repeat;
                    }
                ''')
            input_layout.addWidget(label)

            # 创建输入框
            self.inputs[key] = QLineEdit()
            self.inputs[key].setText(default)
            self.inputs[key].setAlignment(Qt.AlignCenter)
            self.inputs[key].setFixedWidth(300)
            self.inputs[key].setFixedHeight(40)
            self.inputs[key].setFont(QFont("Microsoft YaHei", 12))
            self.inputs[key].setStyleSheet('''
                QLineEdit {
                    border: none;
                    color: white;
                    background-image: url(pic/anniu.png);
                    background-position: center;
                    background-repeat: no-repeat;
                }
            ''')
            input_layout.addWidget(self.inputs[key])

            # 添加到主布局
            self.vBoxLayout.addLayout(input_layout)

        # 添加状态标签
        self.status_label = QLabel("准备就绪")
        self.status_label.setFont(QFont("Microsoft YaHei", 14))
        self.status_label.setAlignment(Qt.AlignCenter)
        self.vBoxLayout.addWidget(self.status_label)

        # 添加进度条
        self.progress = QProgressBar()
        self.progress.setFixedWidth(400)
        self.progress.setFixedHeight(30)
        self.progress.hide()
        self.vBoxLayout.addWidget(self.progress, alignment=Qt.AlignCenter)

        # 减少进度条和按钮之间的间距
        self.vBoxLayout.addSpacing(40)  # 减少间距

        # 创建水平布局来居中放置按钮
        button_layout = QHBoxLayout()
        button_layout.setAlignment(Qt.AlignCenter)

        # 添加运行按钮
        self.run_button = PrimaryPushButton('')  # 删除按钮文字
        pixmap = QPixmap("pic/kaishiyunxing.png")
        self.run_button.setFixedSize(pixmap.size())  # 设置按钮大小与图片一致
        self.run_button.setStyleSheet('''
            PrimaryPushButton {
                border: none;
                background-image: url(pic/kaishiyunxing.png);
                background-position: center;
                background-repeat: no-repeat;
                background-color: transparent;
            }
            PrimaryPushButton:hover {
                background-color: transparent;
            }
            PrimaryPushButton:pressed {
                background-color: transparent;
            }
        ''')
        self.run_button.clicked.connect(self.run_all)
        button_layout.addWidget(self.run_button)
        self.vBoxLayout.addLayout(button_layout)

        # 减少底部空白
        self.vBoxLayout.addStretch(1)  # 减少底部拉伸

    def update_status(self, message, progress=None):
        """更新状态显示"""
        self.status_label.setText(message)
        if progress is not None:
            self.progress.setValue(progress)
        self.repaint()

    def run_all(self):
        """执行完整的路径规划流程"""
        try:
            self.run_button.setEnabled(False)
            self.progress.show()
            self.progress.setValue(0)

            # 1. 生成环境矩阵 (20%)
            self.update_status('正在生成环境矩阵...', 0)
            rows = int(self.inputs['rows'].text())
            cols = int(self.inputs['cols'].text())
            obstacles = int(self.inputs['obstacles'].text())
            MatrixModule.generate_matrix(rows, cols, obstacles)
            self.update_status('环境矩阵生成完成', 20)

            # 2. 生成点对 (40%)
            self.update_status('正在生成路径点对...', 20)
            num_points = int(self.inputs['points'].text())
            PointsModule.generate_point_pairs(num_points)
            self.update_status('点对生成完成', 40)

            # 3. 组合数据 (50%)
            self.update_status('正在组合数据...', 40)
            CombinerModule.combine_files()
            self.update_status('数据组合完成', 50)

            # 4. 象限处理 (60%)
            self.update_status('正在进行象限处理...', 50)
            QuadrantModule.process_and_save_quadrants()
            self.update_status('象限处理完成', 60)

            # 5. 路径规划 (80%)
            self.update_status('正在进行路径规划...', 60)

            current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            data_dir = os.path.join(current_dir, "data")

            total_cost = 0  # 总成本（路径长度）
            successful_paths = 0  # 成功规划的路径数量
            total_requested = 0  # 总请求的点对数
            quadrant_results = []

            # 对每个象限进行路径规划
            for i in range(1, 5):
                quadrant_file = os.path.join(data_dir, f"quadrant_{i}.txt")
                if not os.path.exists(quadrant_file):
                    continue

                try:
                    # 调用规划函数
                    result, requested_paths, path_cost = run_path_planning(quadrant_file, "CBS")
                    total_requested += requested_paths  # 累加这个象限的点对数

                    if result and result.get('paths'):
                        total_cost += path_cost
                        successful_paths += len(result['paths'])
                        result['quadrant'] = i
                        quadrant_results.append(result)

                except Exception as e:
                    print(f"象限{i}规划错误: {str(e)}")
                    continue

            # 统计和显示结果
            if successful_paths > 0:
                success_rate = f"{successful_paths}/{total_requested}"
                self.update_status(f'路径规划完成! 成功率: {success_rate}', 80)

                # 保存结果
                if quadrant_results:
                    output_file = os.path.join(data_dir, "planning_results.json")
                    with open(output_file, 'w', encoding='utf-8') as f:
                        json.dump(quadrant_results, f, indent=4)

                # 计算空域大小
                airspace_size = f"{rows}*{cols}"

                # 将统计结果写入文件
                result_file = os.path.join(data_dir, "total_cost.txt")
                with open(result_file, 'a', encoding='utf-8') as f:
                    f.write(f"{total_requested},{total_cost},{obstacles},{airspace_size}\n")

                # 显示动画
                self.update_status('正在加载3D动画...', 90)
                maps, starts, goals, paths = self._load_visualization_data()
                if any(maps) and any(paths):
                    self.animation_window = Animation3D(maps, starts, goals, paths)
                    self.animation_window.show()
                    self.update_status(f'全部完成! 路径规划成功率: {success_rate}', 100)
                else:
                    self.update_status('完成，但没有可显示的路径', 100)

                InfoBar.success(
                    title='成功',
                    content=f'一键运行完成，路径规划成功率: {success_rate}',
                    orient=Qt.Horizontal,
                    isClosable=True,
                    position=InfoBarPosition.TOP,
                    duration=2000,
                    parent=self
                )
            else:
                raise Exception("所有路径规划都失败了")

        except Exception as e:
            self.update_status(f'执行失败: {str(e)}')
            InfoBar.error(
                title='错误',
                content=str(e),
                orient=Qt.Horizontal,
                isClosable=True,
                position=InfoBarPosition.TOP,
                duration=4000,
                parent=self
            )
        finally:
            self.run_button.setEnabled(True)

    def _load_visualization_data(self):
        """加载可视化所需的数据"""
        from animation_interface import AnimationInterface
        interface = AnimationInterface(self)
        return interface.load_data()

    def resizeEvent(self, event):
        """重写调整大小事件以确保图片始终填满界面"""
        super().resizeEvent(event)
        self.bg_image.setGeometry(0, 0, self.view.width(), self.view.height())